package com.dev.springBootDemo.proxy2;

import com.dev.springBootDemo.proxy.Star;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author zhumq
 * @date 2024/7/2 21:41
 */
public class ProxyUtil {
    // 为用户业务对象创建代理
    public static UserService createProxy(UserService userService) {
        UserService userServiceProxy = (UserService) Proxy.newProxyInstance(ProxyUtil.class.getClassLoader(), new Class[]{UserService.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if ("login".equals(method.getName()) || "deleteUser".equals(method.getName())
                        || "selectUsers".equals(method.getName())) {

                    long startTime = System.currentTimeMillis();

                    Object s = method.invoke(userService, args);

                    long endTime = System.currentTimeMillis();

                    System.out.println(method.getName() + "方法耗时：" + (endTime - startTime) / 1000 + "s");

                    return s;
                } else {
                    return method.invoke(userService, args);
                }
            }
        });
        return userServiceProxy;
    }
}
